package com.mobeedom.android.justinstalled;

import java.io.File;
import java.io.IOException;

import android.os.Environment;
import android.util.Log;

public class AppSingleton {
	private static AppSingleton instance;
    public final static String APP_PNAME = "com.mobeedom.android.justinstalled";
	
	public static final String LOG_TAG = "MLT_JUST";
	public static int NUM_APPS = 5;
	
	public static synchronized AppSingleton getInstance() {
		if (null == instance) {
			instance = new AppSingleton();
		}
		return instance;
	}

	static public boolean hasStorage(boolean requireWriteAccess) {
		String state = Environment.getExternalStorageState();
		Log.v(LOG_TAG, "storage state is " + state);

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			if (requireWriteAccess) {
				boolean writable = checkFsWritable();
				Log.v(LOG_TAG, "storage writable is " + writable);
				return writable;
			} else {
				return true;
			}
		} else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return true;
		}
		return false;
	}

	private static boolean checkFsWritable() {
		// Create a temporary file to see whether a volume is really writeable.
		// It's important not to put it in the root directory which may have a
		// limit on the number of files.
		String directoryName = Environment.getExternalStorageDirectory().toString() + "/tmp";
		File directory = new File(directoryName);
		if (!directory.isDirectory()) {
			if (!directory.mkdirs()) {
				return false;
			}
		}
		File f = new File(directoryName, ".probe");
		try {
			// Remove stale file if any
			if (f.exists()) {
				f.delete();
			}
			if (!f.createNewFile()) {
				return false;
			}
			f.delete();
			return true;
		} catch (IOException ex) {
			return false;
		}
	}

	public static String buildFileName(String base, String ext) {
		return "rec" + base + ext;
	}

}
